package com.airclick.merchant.utils;


//import org.apache.commons.lang.StringUtils;
import com.alibaba.cloud.commons.lang.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.Map.Entry;

/**
 * Create by hackbomb on 2020/7/28 3:39 PM
 * @author caiwangjue
 */
public class MapUtil {

	private MapUtil() {
	}

	/**
	 * Map key 排序
	 *
	 * @param map
	 * @return
	 */
	public static Map<String, String> order(Map<String, String> map) {
		HashMap<String, String> tempMap = new LinkedHashMap<String, String>();
		List<Entry<String, String>> infoIds = new ArrayList<Entry<String, String>>(map.entrySet());

		Collections.sort(infoIds, new Comparator<Entry<String, String>>() {
			@Override
			public int compare(Entry<String, String> o1, Entry<String, String> o2) {
				return (o1.getKey()).compareTo(o2.getKey());
			}
		});

		for (int i = 0; i < infoIds.size(); i++) {
			Entry<String, String> item = infoIds.get(i);
			tempMap.put(item.getKey(), item.getValue());
		}
		return tempMap;
	}

	/**
	 * url 参数串连
	 *
	 * @param map
	 * @param keyLower
	 * @param valueUrlencode
	 * @return
	 */
	public static String mapJoin(Map<String, String> map, boolean keyLower, boolean valueUrlencode) {
		StringBuilder stringBuilder = new StringBuilder();
		Set<Entry<String, String>> entrySet = map.entrySet();
		for (Entry<String, String> entry : entrySet) {
			if (entry.getKey() != null && !"".equals(entry.getValue())) {
				String key = entry.getKey();
				try {
					String temp = (key.endsWith("_") && key.length() > 1) ? key.substring(0, key.length() - 1) : key;
					stringBuilder.append(keyLower ? temp.toLowerCase() : temp)
							.append("=").append(valueUrlencode
									? URLEncoder.encode(entry.getValue(), "utf-8").replace("+", "%20") : entry.getValue())
							.append("&");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		}
		if (stringBuilder.length() > 0) {
			stringBuilder.deleteCharAt(stringBuilder.length() - 1);
		}
		return stringBuilder.toString();
	}

	public static String checkNull(HashMap<String, String> resultMap) {
		Set<Entry<String, String>> entrySet = resultMap.entrySet();
		for (Entry<String, String> entry: entrySet) {
			if (StringUtils.isBlank(entry.getValue())) {
				return entry.getKey();
			} else {
				resultMap.put(entry.getKey(), StringUtils.trim(entry.getValue()));
			}
		}
		return null;
	}

}
